package online.heycm.platform.nacos;

import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;

/**
 * Nacos配置监听器
 *
 * @author heycm
 * @since 2023/11/8 19:25
 */
@Slf4j
public class NacosConfListenerImpl implements NacosConfListener {

    private final NacosProperties nacosProperties;

    private final ConfigService configService;

    public NacosConfListenerImpl(NacosProperties nacosProperties, ConfigService configService) {
        this.nacosProperties = nacosProperties;
        this.configService = configService;
        log.info("Nacos监听器注册配置: {}", nacosProperties);
        log.info("Nacos监听器注册: {}", configService);
    }

    @Override
    public void addListener(String dataId, NacosConfReceiver receiver) {
        addListener(dataId, nacosProperties.getGroup(), receiver);
    }

    @Override
    public void addListener(String dataId, String group, NacosConfReceiver receiver) {
        log.info("注册[dataId: {}, group: {}]配置监听", dataId, group);
        try {
            String config = configService.getConfigAndSignListener(dataId, group, 3000L, new AbstractListener() {
                @Override
                public void receiveConfigInfo(String config) {
                    log.info("收到[dataId: {}, group: {}]配置更新: {}", dataId, group, config);
                    receiver.receiveConf(config);
                }
            });
            // boot init receive
            receiver.receiveConf(config);
        } catch (NacosException e) {
            log.info("注册监听器发生异常", e);
        }
    }
}
